package com.guldan.auth.web.controller;

import com.guldan.auth.common.base.BaseController;
import com.guldan.core.dubbo.client.ResponseDTO;
import com.guldan.core.response.ResponseJson;
import com.guldan.core.utils.ValidateCodeUtil;
import com.guldan.jaina.dto.users.UsersDTO;
import com.guldan.jaina.provider.IAuthorityProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Silas.
 * Date: 2016/10/1
 * Time: 22:38
 */
@Controller
public class IndexController extends BaseController {

    @Autowired
    private IAuthorityProvider iAuthorityProvider;

    @Value("${app.url}")
    private String appUrl;

    //登录页面路由
    @RequestMapping("/")
    public ModelAndView index(HttpServletRequest request,
                              HttpServletResponse response,
                              HttpSession session) {

        ModelAndView modle = new ModelAndView("index");
        //modle.addObject("msg","123");
        return modle;
    }

    @RequestMapping(value = "json", method = RequestMethod.GET)
    @ResponseJson
    public
    @ResponseBody
    String json() {
        return "hello guldan";
    }


    //接收登录请求提交页面
    @RequestMapping("/login")
    public String login(@CookieValue(value = "JSESSIONID", defaultValue = "") String JSESSIONID,
                        HttpServletRequest request,
                        HttpServletResponse response,
                        HttpSession session, Model model) {
        String userAccount = request.getParameter("username");
        String password = request.getParameter("password");
        String service = request.getParameter("service") == null ? appUrl : request.getParameter("service");


        String token = UUID.randomUUID().toString();

        String rand = request.getParameter("rand") == null ? "" : request.getParameter("rand").toLowerCase();

        logger.info("rand: " + rand + " username: " + userAccount + ", password: " + password + ", token: " + token);

        //验证验证码
        if (session.getAttribute("rand") != null && !rand.equals(session.getAttribute("rand").toString())) {
            //不通过
            model.addAttribute("msg", "验证码错误");
            return "index";
        }

        //验证帐号密码，并创建token，回传给client
        ResponseDTO<UsersDTO> responseDTO = iAuthorityProvider.login(userAccount, password, token);
        if (responseDTO.getData() != null) {
            //登录成功

            logger.info("username: " + userAccount + " login success, token: " + token);

            return "redirect:" + (service.equals("") ? appUrl : service) + "?token=" + token;
        } else {
            model.addAttribute("msg", "帐号or密码错误");
            return "index";
        }

    }


    //退出登录
    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request,
                           HttpServletResponse response,
                           HttpSession session) {
        String JSESSIONID = request.getParameter("jsessionid");
        String service = request.getParameter("service") == null ? appUrl : request.getParameter("service");


        //退出登录
        ResponseDTO<Boolean> responseDTO = iAuthorityProvider.loginOut(JSESSIONID);
//        if (responseDTO.getData()) {
        //退出成功 /?service=http://139.170.248.86:9002
        return "redirect:/?service=" + (service.equals("") ? appUrl : service);
//        } else
//            return "index";
    }

    //获取验证码
    @RequestMapping(value = "/validateCode", method = RequestMethod.GET)
    public void login(HttpServletRequest request,
                      HttpServletResponse response,
                      HttpSession session) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串
        String verifyCode = ValidateCodeUtil.generateVerifyCode(4);
        //存入会话session
        session.setAttribute("rand", verifyCode.toLowerCase());
        //生成图片
        int w = 200, h = 80;
        try {
            ValidateCodeUtil.outputImage(w, h, response.getOutputStream(), verifyCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
